console.log("Content script loaded");

function waitForElement(selector, callback, interval = 100, timeout = 10000) {
    const startTime = Date.now();

    function checkElement() {
        const element = document.querySelector(selector);
        if (element) {
            callback(element);
        } else if (Date.now() - startTime < timeout) {
            setTimeout(checkElement, interval);
        } else {
            console.error(`Element with selector "${selector}" not found after ${timeout}ms`);
        }
    }

    checkElement();
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "extractSSHInfo") {
        const sshInfo = {};
        console.log('Received request to extract SSH info');

        // 确保页面完全加载
        if (document.readyState === "complete") {
            extractSSHInfo(sshInfo, sendResponse);
        } else {
            window.addEventListener('load', () => {
                extractSSHInfo(sshInfo, sendResponse);
            });
        }

        return true; // 保持消息通道打开，直到发送响应
    }
});

function extractSSHInfo(sshInfo, sendResponse) {
    const promises = [];

    // 获取用户名
    promises.push(new Promise((resolve) => {
        const userSelector = 'p.mb-0.font-size-12 span.text-success';
        waitForElement(userSelector, (userElement) => {
            sshInfo.user = userElement.textContent.trim();
            resolve();
        });
    }));

    // 获取密码
    promises.push(new Promise((resolve) => {
        const passwordSelector = 'p.mb-0.font-size-12 span.text-danger';
        waitForElement(passwordSelector, (passwordElement) => {
            sshInfo.password = passwordElement.textContent.trim();
            resolve();
        });
    }));
    
    // 获取IP地址
    promises.push(new Promise((resolve) => {
        const ipSelector = 'span.target-0';
        waitForElement(ipSelector, (ipElement) => {
            sshInfo.ip = ipElement.textContent.trim();
            resolve();
        });
    }));

    // 检测是否为RDP连接
    promises.push(new Promise((resolve) => {
        const rdpSelector = 'p.mb-0.font-size-12';
        waitForElement(rdpSelector, (rdpElement) => {
            if (rdpElement.textContent.includes('RDP')) {
                sshInfo.isRDP = true;
            } else {
                sshInfo.isRDP = false;
            }
            resolve();
        });
    }));

    Promise.all(promises).then(() => {
        if (sshInfo.isRDP) {
            sshInfo.command = `xfreerdp /v:${sshInfo.ip} /u:${sshInfo.user} /p:${sshInfo.password}`;
        } else {
            sshInfo.command = `ssh ${sshInfo.user}@${sshInfo.ip}`;
        }
        sendResponse(sshInfo);
    });
}


